import React, { useState, useRef, useEffect } from 'react'
import { Form, Layout, Switch, Table, Select, Modal, Input, Button, Space, message, Tooltip } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import Highlighter from 'react-highlight-words'
import '../child/ContentStyle.css'
import axios from 'axios'


const { Content } = Layout
const { Option } = Select
//用户列表
export default function UserList () {
  const [data, setData] = useState([])
  const [roleList, setRoleList] = useState([])
  const [changeRoleFlag, setChangeRoleFlag] = useState('')

  useEffect(() => {
    axios.get("http://localhost:8081/userList/getUserList",
      {
        headers: {
          satoken: localStorage.getItem("satoken")
        }
      }
    ).then(r => {
      if (r.data.code !== 200) {
        message.error(r.data.msg)
      } else {
        //设置表格数据
        setData(r.data.data.userList)
        //设置下拉框中的角色列表
        setRoleList(r.data.data.roleList)
      }
    })
  }, [changeRoleFlag]) //监听改变角色的标志位

  //获取表格中的数据
  const getDatas = (datas) => {
    let tableData = datas
    let i = 1
    tableData.map((item) => {
      item.key = i++
      return item
    })
    return tableData
  }

  //改变用户状态
  const onChange = async (e, record) => {

    await axios({
      url: "http://localhost:8081/userList/changeUserStatus",
      method: "post",
      data: {
        flag: e,
        username: record.username
      },
      headers: {
        'satoken': localStorage.getItem("satoken")
      },
    }).then(r => {
      if (r.data.code === 200) {
        message.success("设置成功")
      } else {
        message.error("设置失败，请联系站长")
      }
    })
  }

  //角色选择框的操作
  const handleChange = async (data, value) => {
    await axios({
      url: "http://localhost:8081/userList/changeUserRole",
      method: "post",
      data: {
        roleName: value,
        username: data.username
      },
      headers: {
        'satoken': localStorage.getItem("satoken")
      },
    }).then(r => {
      if (r.data.code === 200) {
        //将表格数据清空，通知页面刷新
        //setData([])
        message.success(r.data.msg)
        //这个标志位呗监听，用于重新渲染
        setChangeRoleFlag(value)
      } else {
        message.error(r.data.msg)
      }
    })
  }

  //提交新建用户的表单
  const onFinish = async (values) => {
    await axios({
      url: "http://localhost:8081/userList/insertNewUser",
      method: "post",
      data: {
        username: values.username,
        password: values.password,
        role: values.role
      },
      headers: {
        'satoken': localStorage.getItem("satoken")
      },
    }).then(r => {
      if (r.data.code === 200) {
        message.success(r.data.msg)
        //关闭对话框
        setIsModalVisible(false)
        //强制重新渲染
        setChangeRoleFlag(values.username)
      } else {
        message.error(r.data.msg)
      }
    })

  }
  //提交新建用户失败
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo)
  }

  /***  以下是表格中搜索功能  ******************/
  const [searchText, setSearchText] = useState('')
  const [searchedColumn, setSearchedColumn] = useState('')
  const searchInput = useRef(null)

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm()
    setSearchText(selectedKeys[0])
    setSearchedColumn(dataIndex)
  }

  const handleReset = (clearFilters) => {
    clearFilters()
    setSearchText('')
  }

  const getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div
        style={{
          padding: 8,
        }}
      >
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: 'block',
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            Search
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            Reset
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({
                closeDropdown: false,
              })
              setSearchText(selectedKeys[0])
              setSearchedColumn(dataIndex)
            }}
          >
            Filter
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        style={{
          color: filtered ? '#1890ff' : undefined,
        }}
      />
    ),
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100)
      }
    },
    render: (text) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{
            backgroundColor: '#ffc069',
            padding: 0,
          }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (
        text
      ),
  })

  /***  以上是表格中搜索功能  ******************/


  const [isModalVisible, setIsModalVisible] = useState(false)

  //展示对话框
  const showModal = () => {
    setIsModalVisible(true)
  }

  //ok按钮
  const handleOk = () => {
    setIsModalVisible(false)
  }

  //cancel按钮
  const handleCancel = () => {
    setIsModalVisible(false)
  }

  //删除用户的操作
  const deleteUser = async (data, recode) => {
    await axios({
      url: "http://localhost:8081/userList/deleteUser",
      method: "post",
      data: {
        username: recode.username,
      },
      headers: {
        'satoken': localStorage.getItem("satoken")
      },
    }).then(r => {
      if (r.data.code === 200) {
        message.success(r.data.msg)

        //强制重新渲染
        setChangeRoleFlag(recode.username + "delete")
      } else {
        message.error(r.data.msg)
      }
    })
  }

  // 表格的字段，删除按钮在里面
  const columns = [
    {
      title: '用户名',
      align: 'center',
      width: '10%',
      dataIndex: 'username',
      //搜索框
      ...getColumnSearchProps('username')
    },
    {
      title: '角色',
      align: 'center',
      width: '15%',
      dataIndex: 'role',
      ...getColumnSearchProps('role'),
      render: (data, recode) =>
        <Select
          defaultValue={data}
          style={{
            width: 120,
          }}
          onChange={(optionValue) => { handleChange(recode, optionValue) }}
        >
          {roleList.map((item) => {
            if (item.status === 1) {
              return <Option key={item.description} value={item.description}>{item.description}</Option>
            } else {
              return <Option key={item.description} value={item.description} disabled>{item.description}</Option>
            }
          })}
        </Select >
    },
    {
      title: '菜单按钮',
      align: 'center',
      width: '50%',
      dataIndex: 'menus',
      ellipsis: {
        showTitle: false,
      },
      //弹出工具框
      render: (menus) => (
        <Tooltip placement="topLeft" title={menus}>
          {menus}
        </Tooltip>
      ),
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'status',
      key: 'status',
      render: (data, record) => <Switch defaultChecked={data === 1 ? true : false} onChange={(check) => onChange(check, record)} />
    },
    {
      title: '删除',
      align: 'center',
      dataIndex: 'delete',
      key: 'delete',
      render: (data, record) => <Button type="primary" onClick={() => { deleteUser(data, record) }}>删除</Button>,
    }
  ]

  return (
    <Content className='userlistContent'>
      {/* 添加用户按钮 */}
      <Button
        type="primary"
        onClick={showModal}
        style={{
          width: 100,
          marginTop: 25,
          marginRight: 20,
          float: 'right',
          marginBottom: 20
        }}>
        添加用户
      </Button>

      {/* 表格 */}
      <Table
        bordered
        columns={columns}
        dataSource={getDatas(data)}
        pagination={{ pageSize: 7 }}//自定义每页显示的数据条数
      ></Table>

      {/* 创建用户的对话框 */}
      <Modal title="新建用户" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Form
          name="basic"
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
            ]}
          >
            <Input placeholder="请勿与之前的用户重名" />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}
          >
            <Input placeholder="请将密码设置的复杂点" />
          </Form.Item>

          <Form.Item
            label="角色"
            name="role"
            rules={[
              {
                required: true,
                message: '请选择角色',
              },
            ]}
          >
            <Select
              placeholder="请为新用户选择角色"

            >
              {roleList.map((item) => {
                if (item.status === 1) {
                  return <Option key={item.description} value={item.description}>{item.description}</Option>
                } else {
                  return <Option key={item.description} value={item.description} disabled>{item.description}</Option>
                }
              })}
            </Select >
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 5,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>

    </Content>

  )
}
